<template>
  <div style="padding: 15px;display: flex;">
    <div class="j-tree">
      <div style="text-align: right;margin-bottom: 10px;" v-if="allowAddPid">
        <JButton type="info" circle icon="Plus" size="small" text="新增" @click="addPid" />
      </div>
      <div :style="{height: hei+'px'}" style="overflow: auto;">
        <tiny-tree
            ref="treeRef"
            node-key="id"
            :data="data"
            current-node-key="1"
            :default-expand-all="expandAll"
            :show-checkbox="showCheckbox"
            :props="treeProps"
            @open-edit="onOpenEdit"
            @close-edit="onCloseEdit"
            @save-edit="onSaveEdit"
            @add-node="onAddNode"
            @edit-node="onEditNode"
            @delete-node="onDeleteNode"
            @node-click="nodeClick"
            :delete-node-method="deleteNodeMethod"
        />
      </div>
    </div>
    <div style="width: 500px;padding-left: 30px;" v-if="rules.length > 0">
      <fieldset style="padding: 10px;border-color: rgba(0,0,0,0.07);border-radius: 4px;">
        <legend>节点信息</legend>
        <div style="padding: 10px;">
          <x-form :rules="rules" v-model="formModel" v-model:api="fApi"></x-form>
          <div style="height: 20px;"></div>
          <div style="text-align: center;">
            <JButton @click="save" type="info">保存</JButton>
          </div>
        </div>
      </fieldset>
    </div>
  </div>

</template>

<script setup>
import tool from "@/utils/tool";
import { TinyTree, TinyModal } from '@opentiny/vue'
import {ref, onMounted, computed, getCurrentInstance, nextTick, watch} from "vue";
import JButton from '@/lui/JButton.vue'
import XForm from "@/lui/XForm.vue";
const {proxy} = getCurrentInstance()
const route = proxy.$route
const props = defineProps({
  labelKey: {type: String, default: 'name'},
  height: {type: [String,Number], default: 0},
  saveUrl: {type: String, default: ''},
  listUrl: {type: String, default: ''},
  delUrl: {type: String, default: ''},
  mod: {type: String, default: ''},
  expandAll: {type: Boolean, default: false},
  showCheckbox: {type: Boolean, default: false},
  showCode: {type: Boolean, default: false},
  allowAddPid: {type: Boolean, default: false},
  allowEdit: {type: Boolean, default: false},
  list: {type: Array, default: () => { return [] }},
  rules: {type: Array, default: () => { return [] }},
})
const treeProps = ref({
  children: 'children',
  label: props.labelKey,
})
const data = ref([])
const treeRef = ref()
const fApi = ref({})
const formModel = ref({})
const hei = computed(() => {
  if(props.height) {
    return props.height
  }
  else {
    return window.innerHeight - 150
  }
})

function openEdit() {
  treeRef.value.openEdit()
}
function closeEdit() {
  treeRef.value.closeEdit()
}
function saveEdit() {
  data.value = treeRef.value.saveEdit()
}
const save = () => {
  if(props.saveUrl) {
    tool.post(props.saveUrl,{
      mod: props.mod,
      formData: formModel.value,
      whichPage:"menuList"
    },true).then(ret => {

    })
  }
}
const nodeClick = (data) => {
  if(props.rules.length > 0) {
    formModel.value = data
  }
}

function onOpenEdit() {}
function onCloseEdit() {

}
function onSaveEdit(changedData, finalData) {
}
function onAddNode(addedNode) {
  let parentData = addedNode.parent.data
  let data = addedNode.data
  let pass = {
    pid: parentData.id,
    name: data.label,
  }
  tool.post(props.saveUrl, {whichPage: route.name,mod: props.mod, formData: pass}, true).then(ret => {
   getList()
  })
}

function onEditNode(editNode) {
  let node = editNode.data
  if(node.label) {
    if(node.label !== node.name) {
      tool.post(props.saveUrl, {
        whichPage: route.name,
        mod: props.mod,
          formData: {
             name: node.label, id: node.id
          }
        }, true).then(ret =>{
        getList()
      })
    }
  }
}
function onDeleteNode(deletedNode) {

}
// 新增一级分类
const addPid = () => {
  tool.editor({
    title: '新增顶级分类',
    width: 500,
    height: 200,
    mounted: () => {},
    rules: [
      {field: 'label', title: '名称', com: 'JInput', required: true}
    ],
    btns: [{
      name: "保存",click: (inject, close) => {
        if(inject.valid()) {
          let data = inject.getFormData()
          tool.post(props.saveUrl, {whichPage: route.name, mod: props.mod, formData: {pid: 0, name: tool.xe.trim(data.label) }}, true).then(ret => {
            if(ret.stat) {
              close()
              getList()
            }
          })

        }
      }
    }]
  })
}

function deleteNodeMethod({node}) {
  if(node.childNodes.length > 0) {
    return tool.err('请先删除子分类')
  }

  // 方式 2：返回 Promise 异步
  return new Promise((resolve) => {
    TinyModal.confirm({
      title: '删除提示',
      status: 'info',
      message: '您确定要删除节点数据吗？',
      events: {
        confirm() {
          tool.post(props.delUrl, {id: node.data.id, mod: props.mod, whichPage: route.name}).then(ret => {
            if(ret.stat) {
              resolve(true)
            }
          })
        },
        cancel() {
          resolve(false)
        }
      }
    })
  })
}

const getChecked = () => {
  let half = treeRef.value.getHalfCheckedNodes()
  let checked = treeRef.value.getCheckedNodes()
  let arr = []
  half.map(row => {
    arr.push({id: row.id})
  })
  checked.map(row => {
    arr.push({id: row.id})
  })
  return arr
}
const setChecked = (id) => {
   treeRef.value.setChecked(id, true, false)
}
const getList = () => {
  if(props.listUrl)
    tool.post(props.listUrl, {whichPage: route.name, formData: {}}).then(ret => {
      if(ret.stat) {
        ret.data.list.map(row => {
          row.label = row.name
        })
        data.value = tool.toArrayTree(ret.data.list)
      }
    })
}
//----------------------------------------------------



const nodeDrop = (current, after) => {
  let list = after.parent.childNodes
  let arr = []
  for (let i = 0; i < list.length; i++) {
    arr.push({
      id: list[i].data.id,
      sort: i
    })
  }
  tool.post('common/doSort', {formData: arr, mod: props.mod})
}

onMounted(() => {
  if(props.allowEdit) {
    treeRef.value.openEdit()
  }
  if(props.listUrl) {
    getList()
  }
  if(props.list.length > 0) {
    data.value = tool.toArrayTree(props.list)
    nextTick(() => {
      for (let i = 0; i < props.list.length; i++) {
        if(props.list[i].checked) {
          treeRef.value.setChecked(props.list[i].id, true)
        }
      }
    })
  }
})


defineExpose({getChecked, setChecked})

</script>

<style  lang="scss">
.j-tree {
  max-width: 600px;
  width: 400px;
}

</style>
